package user

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"zhou_gin_api/app/input"
	"zhou_gin_api/app/output/code"
	"zhou_gin_api/app/service/command/user"
	"zhou_gin_api/app/service/query/userQuery"
	"zhou_gin_api/app/validate"
)

func Index(c *gin.Context) {

	var userRequest input.IndexUserInput

	if err := c.ShouldBindQuery(&userRequest); err != nil {
		validate.Translate(err, c)
		return
	}

	//appLog.InfoSimpleLog("请求用户列表")

	service := userQuery.NewUserQueryService()
	userOutputs := service.Index(userRequest)
	c.Set("data", userOutputs)

}

func Add(c *gin.Context) {

	var userRequest input.AddUserInput

	if err := c.ShouldBindJSON(&userRequest); err != nil {
		validate.Translate(err, c)
		return
	}

	userService := user.NewUserCommandService()

	id, err := userService.Add(userRequest)
	if err != nil {
		c.Set("code", code.ResponseCode["EXCEPTION_MESSAGE"])
		c.Set("msg", err.Error())
		return
	}

	c.Set("data", gin.H{
		"id": id,
	})
}

func Update(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.Set("code", code.ResponseCode["EXCEPTION_MESSAGE"])
		c.Set("msg", "url参数格式不正确")
		return
	}

	var userRequest input.UpdateUserInput

	if err := c.ShouldBind(&userRequest); err != nil {
		validate.Translate(err, c)
		return
	}
	userRequest.Id = uint(id)
	userService := user.NewUserCommandService()

	errCode, msg := userService.Update(userRequest)

	c.Set("code", errCode)
	c.Set("msg", msg)
}

func Delete(c *gin.Context) {

	var userRequest input.DeleteUserInput

	if err := c.ShouldBindUri(&userRequest); err != nil {
		validate.Translate(err, c)
		return
	}

	userService := user.NewUserCommandService()

	errCode, msg := userService.Delete(userRequest)
	c.Set("code", errCode)
	c.Set("msg", msg)
}

func Show(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.Set("code", code.ResponseCode["EXCEPTION_MESSAGE"])
		c.Set("msg", "url参数格式不正确")
		return
	}

	service := userQuery.NewUserQueryService()
	userModel, errCode, msg := service.Show(uint(id))

	c.Set("code", errCode)
	c.Set("msg", msg)
	c.Set("data", userModel)
}
